import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:music_app/api/dio_client.dart';
// 播放业务控制器
import 'package:music_app/controllers/audio_player_controller.dart';
import 'package:music_app/controllers/route_observer_with_player.dart';
// 底部栏显示控制器
import 'package:music_app/player/bottom_player_overlay_controller.dart';
import 'package:music_app/routes/index.dart';
import 'package:music_app/theme/index.dart';

void main() async {
  // main函数中使用异步初始化时，必须先调用这个方法，确保绑定已经建立
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化dio
  await DioUtil().init();
  // 注册播放业务控制器
  Get.put(AudioPlayerController());
  // 注册 overlay 底部播放器控制器
  Get.put(BottomPlayerOverlayController());
  // 启动app
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: '网易云音乐app',
      debugShowCheckedModeBanner: false,
      theme: AppTheme.light,
      darkTheme: AppTheme.dark,
      themeMode: ThemeMode.system, // 跟随系统
      initialRoute: '/main', // 初始页面
      getPages: AppPages.routes, // 路由配置
      builder: (context, child) {
        return OverlayWrapper(child: child!);
      },
      navigatorObservers: [RouteObserverWithPlayer()], // 注册自定义的导航观察器
    );
  }
}

// Overlay 包装组件 实现底部音乐导航栏的全局展示
class OverlayWrapper extends StatelessWidget {
  final Widget child;

  const OverlayWrapper({super.key, required this.child});

  @override
  Widget build(BuildContext context) {
    final overlayController = Get.find<BottomPlayerOverlayController>();
    // 添加帧回调，确保 Overlay 初始化
    WidgetsBinding.instance.addPostFrameCallback(
      (_) {
        overlayController.initOverlay(context);
      },
    );
    return child;
  }
}
